// $Id: webfm_popup.js,v 1.1 2009/02/08 06:27:11 robmilne Exp $

function webfm_popup() {}

if (Drupal.jsEnabled) {
  $(window).load(webfm_popupGetMenusAjax);
}

// Add the send to rich text editor link to the right click menu of files.
function webfm_popupGetMenusAjax() {
  var doc = $(window.opener.document);
  Webfm.menuHT.put('file', new Webfm.menuElement("Invia all'editor", webfm_popup.sendtocaller, ""));
}

// Send the selected file to the rich text editor.
webfm_popup.sendtocaller = function(obj) {
  // put the webfm file-id in the input with the id specified in the url
  var fid = $('#'+obj.row_id).find('td').eq(1).find('a').attr('title');
  var fpath = 'webfm_send/' + fid;
  var webfm_id = get_url_param('webfmid');
  
  var document = window.opener.document;
  var myField = document.getElementById(webfm_id);

  if(document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = fpath;
  }
  //other browsers
  else if(myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)+ fpath + myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += fpath;
  }

  window.opener.focus();
  window.close();
}

// read GET parameter from the url
// for example on the url http://example.com/page.php?some=value&more=evenmore&get_it=yes
// calling get_url_param('get_it') would return 'yes'
function get_url_param(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null ) return "";
	else return results[1];
}
